<?php
/**
 * 熵巡 - 企业级氚云OpenAPI数据管理平台
 * 开发归属 Alyr.net
 * 通用数据获取接口
 * 尊重劳动成果是一种美德
 */

error_reporting(0);
ini_set('display_errors', 0);

// ========================================
// 配置区域：Token 与表单映射关系
// ========================================
$tokenMapping = [
    // 示例表单1
    'TokenID001' => [
        'token_id' => 'TokenID001',
        'token_secret' => 'TokenSecret001xxxxxxxxxxxx',
        'schema_code' => 'SchemaCodeExample001xxxxxxxxxxxxxxxxxxxxxx',
        'schema_key' => 'default',
        'name' => '示例表单1',
        'image_fields' => ['F0000001', 'F0000002'],
        'attachment_fields' => ['F0000003']
    ],
    // 示例表单2
    'TokenID002' => [
        'token_id' => 'TokenID002',
        'token_secret' => 'TokenSecret002xxxxxxxxxxxx',
        'schema_code' => 'SchemaCodeExample002xxxxxxxxxxxxxxxxxxxxxx',
        'schema_key' => 'schema_example',
        'name' => '示例表单2',
        'image_fields' => ['F0000001', 'F0000002'],
        'attachment_fields' => ['F0000003']
    ]
];

// H3yunApi 内部路径配置（请替换为您的实际域名）
$h3yunApiBaseUrl = 'https://your-domain.com/api';

// ========================================
// 功能路由：支持多种操作
// ========================================
$action = $_GET['action'] ?? 'get_data';

// 处理获取Token配置的请求
if ($action === 'get_tokens') {
    // 将关联数组转换为索引数组，供前端forEach使用
    $tokensArray = array_values($tokenMapping);
    
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode([
        'success' => true,
        'tokens' => $tokensArray,
        'api_base_url' => $h3yunApiBaseUrl  // 返回API基础URL
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

// 处理获取单个Token配置的请求
if ($action === 'get_token') {
    $tokenId = $_GET['token_id'] ?? '';
    
    header('Content-Type: application/json; charset=utf-8');
    
    if (empty($tokenId)) {
        echo json_encode(['success' => false, 'message' => '缺少token_id参数'], JSON_UNESCAPED_UNICODE);
        exit;
    }
    
    if (!isset($tokenMapping[$tokenId])) {
        echo json_encode(['success' => false, 'message' => '无效的token_id'], JSON_UNESCAPED_UNICODE);
        exit;
    }
    
    echo json_encode([
        'success' => true,
        'token' => $tokenMapping[$tokenId]
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

// 默认的数据获取功能
try {
    header('Content-Type: application/json; charset=utf-8');
    
    $tokenId = $_GET['token_id'] ?? '';
    $tokenSecret = $_GET['token_secret'] ?? '';
    
    // 验证 Token ID 和 Token Secret
    if (empty($tokenId) || empty($tokenSecret)) {
        echo json_encode(['success' => false, 'message' => '缺少token_id或token_secret'], JSON_UNESCAPED_UNICODE);
        exit;
    }
    
    // 根据 token_id 查找对应的表单配置
    if (!isset($tokenMapping[$tokenId])) {
        echo json_encode(['success' => false, 'message' => '无效的token_id'], JSON_UNESCAPED_UNICODE);
        exit;
    }
    
    $config = $tokenMapping[$tokenId];
    
    // 验证 token_secret 是否匹配
    if ($config['token_secret'] !== $tokenSecret) {
        echo json_encode(['success' => false, 'message' => 'Token验证失败'], JSON_UNESCAPED_UNICODE);
        exit;
    }
    
    $schemaCode = $config['schema_code'];
    
    // 获取分页参数
    $requestedPage = max(1, (int)($_GET['page'] ?? 1));
    $requestedSize = min(max(1, (int)($_GET['size'] ?? 100)), 500);
    $keyword = $_GET['keyword'] ?? '';
    
    // 如果请求的是特定页，直接转发
    if (isset($_GET['page'])) {
        $url = $h3yunApiBaseUrl . '/get_data.php?schema_code=' . urlencode($schemaCode) . '&token=' . urlencode($tokenSecret);
        $url .= '&page=' . $requestedPage;
        $url .= '&size=' . $requestedSize;
        
        if (!empty($keyword)) {
            $url .= '&keyword=' . urlencode($keyword);
        }
        
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        $response = curl_exec($ch);
        curl_close($ch);
        
        echo $response;
        exit;
    }
    
    // 否则，自动分页获取所有数据
    $allData = [];
    $currentPage = 1;
    $pageSize = 500; // 使用最大值提高效率
    $maxPages = 100; // 安全限制，最多100页（50000条数据）
    
    while ($currentPage <= $maxPages) {
        $url = $h3yunApiBaseUrl . '/get_data.php?schema_code=' . urlencode($schemaCode) . '&token=' . urlencode($tokenSecret);
        $url .= '&page=' . $currentPage;
        $url .= '&size=' . $pageSize;
        
        if (!empty($keyword)) {
            $url .= '&keyword=' . urlencode($keyword);
        }
        
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
        // 检查请求是否成功
        if ($httpCode !== 200) {
            break;
        }
        
        $result = json_decode($response, true);
        
        // 检查响应格式
        if (!$result || !isset($result['success']) || !$result['success']) {
            break;
        }
        
        $data = $result['data'] ?? [];
        
        // 如果没有数据，说明已经到最后一页
        if (empty($data)) {
            break;
        }
        
        // 合并数据
        $allData = array_merge($allData, $data);
        
        // 如果返回的数据少于请求的数量，说明已经是最后一页
        if (count($data) < $pageSize) {
            break;
        }
        
        $currentPage++;
    }
    
    // 返回合并后的所有数据
    echo json_encode([
        'success' => true,
        'data' => $allData,
        'total' => count($allData),
        'pages' => $currentPage - 1
    ], JSON_UNESCAPED_UNICODE);
    
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()], JSON_UNESCAPED_UNICODE);
}
